//
//  TJVideoCoverDownloader.m
//  BaoDian
//
//  Created by mac on 2024/8/7.
//

#import "TJVideoCoverDownloader.h"

@interface TJVideoCoverDownloader()

@property (nonatomic, strong) NSOperationQueue *operationQueue;
@property (nonatomic, strong) NSMutableDictionary *taskDict;


@end

@implementation TJVideoCoverDownloader

static TJVideoCoverDownloader *_videoCoverDownloader = nil;

- (NSOperationQueue *)operationQueue {
    if (!_operationQueue) {
        _operationQueue = [[NSOperationQueue alloc] init];
        _operationQueue.maxConcurrentOperationCount = 1;
    }
    return _operationQueue;
}

+ (TJVideoCoverDownloader *)shareDownLoader {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_videoCoverDownloader == nil) {
            _videoCoverDownloader = [[TJVideoCoverDownloader alloc] init];
        }
    });
    return _videoCoverDownloader;
}

- (void)downloadWithUrl:(NSString *)url completion:(void (^)(UIImage * _Nullable thumbnail))completion {
    
    if (isEmptyString(url)) {
        completion(nil);
        return;
    };
    
    TJLog(@"下载 %@ 封面图", url);

    NSString *cacheKey = url.md5;
    if ([self.taskDict valueForKey:cacheKey]) {
        return;
    }
    
    [self.taskDict setValue:@{@"url": url} forKey:cacheKey];
    
    [[SDImageCache sharedImageCache] queryImageForKey:cacheKey options:0 context:nil cacheType:SDImageCacheTypeAll completion:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) {
        if (cacheType != SDImageCacheTypeNone && image.size.width) {
            dispatch_async_main_queue(^{
                TJLog(@"取出缓存 %@ 封面图", url);
                [self.taskDict removeObjectForKey:cacheKey];
                completion(image);
            });
        } else {
            [self.operationQueue addOperationWithBlock:^{
                UIImage *image = [TJTools getVideoFirstViewImageWithURL:url.URL];
                if (image && image.size.width) {
                    NSData *imageData = UIImageJPEGRepresentation(image, 0.65);
                    TJLog(@"下载 %@ 封面图完成", url);
                    [[SDImageCache sharedImageCache] storeImageData:imageData forKey:cacheKey completion:^{
                        dispatch_async_main_queue(^{
                            [self.taskDict removeObjectForKey:cacheKey];
                            completion(image);
                        });
                    }];
                } else {
                    [self.taskDict removeObjectForKey:cacheKey];
                }
            }];
        }
    }];
}


@end
